package com.financing.wap.web.controller.api;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.financing.wap.service.IDstIntegralRuleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.common.ResultMap;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.dto.DstUserInfoExpandDTO;
import com.financing.wap.service.ICommonService;
import com.financing.wap.service.IDstUserInfoExpandService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.service.weixin.service.WeixinService;
import com.financing.wap.util.AliyunOssUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.DstUserCountInfoVO;
import com.financing.wap.web.controller.BaseController;

@Controller("dstUserInfoExpandController")
@RequestMapping("/api/dstUserInfoExpand")
public class DstUserInfoExpandController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	private static final  Object obj = new Object();

	@Autowired
	private ICommonService commonService;
	
	@Autowired
	private IDstUserInfoExpandService dstUserInfoExpandService;
	@Autowired
	private IDstUserInfoService dstUserInfoService;
	
	@Autowired
	private WeixinService weixinJincsServiceImpl;

	@Autowired
	private IDstIntegralRuleService dstIntegralRuleService;
	
	// 保存文件到本地目录
	private static String ossUserCardPath = PropertiesUtils.getValue("ossUserCardPath");
	//有二维码名片的背景图
	String hasUserCardImage =PropertiesUtils.getValue("ossBaseDir")+"/mark.jpg";
	//没有二维码名片的背景图
	String noUserCardImage =PropertiesUtils.getValue("ossBaseDir")+"/mark1.jpg";
	
	/***
	 * 用户名片信息  详情
	 * @param request
	 * @return
	 */
	@RequestMapping("/detailDstUserInfoExpand")
	@ResponseBody
	public ResultMap detail(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query detail dstUserInfoExpand  begin .......");
			
			DstUserInfoExpandDTO dstUserInfoExpand=new DstUserInfoExpandDTO();
			String openid = request.getParameter("openid");
			if(StringUtil.isNullOrEmptyStr(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			dstUserInfoExpand.setUserOpenid(openid);
			DstUserInfoExpandDTO dto = dstUserInfoExpandService.queryListGetFirst(dstUserInfoExpand);
			
			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo
					.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);
			dto.setUserNickName(userinfo.getUserName());
			dto.setUserWechatImage(userinfo.getUserWechatImage());
			dto.setFlagConcern(StringUtils.isBlank(userinfo.getFlagConcern())? CommonConstantUtil.UserInfoStatus.FLAG_CONCERN_NO:userinfo.getFlagConcern());
			
			if(StringUtil.isNullOrEmptyStr(dto.getUserName())){
				dto.setUserName(userinfo.getUserName());
			}

			//默认名片显示位置 0 全部 1 上 2 下 3 不显示   默认 0   
			//兼容老版本  
			if(StringUtils.isNotBlank(dto.getUserShow())){
				if("0".equals(dto.getUserShow())){
					dto.setUserShow("结尾,精简");
				}else if("1".equals(dto.getUserShow())){
					dto.setUserShow("开头");
				}else if("2".equals(dto.getUserShow())){
					dto.setUserShow("结尾");
				}else if("3".equals(dto.getUserShow())){
					dto.setUserShow("");
				}
			}else{
				dto.setUserShow("结尾,精简");
			}
			
			result.setAttribute("dto",dto);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query detail dstUserInfoExpand  end .......");
		}catch(Exception e){
			log.error("query detail dstUserInfoExpand error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/***
	 * 修改和新增 用户扩展信息  名片设置
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateDstUserInfoExpand")
	@ResponseBody
	public ResultMap update(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("update dstUserInfoExpand  begin .......");
			String openid = request.getParameter("openid");
			String userName = request.getParameter("userName");
			String userPhone = request.getParameter("userPhone");
			String userCompany = request.getParameter("userCompany");
			String userPosition = request.getParameter("userPosition");
			String userEmail = request.getParameter("userEmail");
			String userAddress = request.getParameter("userAddress");
			String userCardImg = request.getParameter("userCardImg");
			String newPicMediaId = request.getParameter("newPicMediaId");
			String userShow = request.getParameter("userShow");
			if(StringUtil.isNullOrEmptyStr(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			
			synchronized (obj) {
				//微信图片上传
				if(StringUtils.isNotBlank(newPicMediaId)){
					String picAddr = weixinJincsServiceImpl.getFileByMediaId("jpg", newPicMediaId);
					userCardImg=CommonConstantUtil.OSS_PATH+picAddr;
				}
				DstUserInfoExpandDTO addInfo=new DstUserInfoExpandDTO();
				addInfo.setUserOpenid(openid);
				DstUserInfoExpandDTO userInfoExpand = dstUserInfoExpandService.queryListGetFirst(addInfo);
				if(userInfoExpand.getId()==null){
					addInfo.setUserName(userName);
					addInfo.setUserPhone(userPhone);
					addInfo.setUserCardImg(userCardImg);
					addInfo.setUserAddress(userAddress);
					addInfo.setUserEmail(userEmail);
					addInfo.setUserPosition(userPosition);
					addInfo.setUserCompany(userCompany);
					addInfo.setUserShow(userShow);
					dstUserInfoExpandService.insert(addInfo);
				}else{
					userInfoExpand.setUserName(userName);
					userInfoExpand.setUserPhone(userPhone);
					userInfoExpand.setUserCardImg(userCardImg);
					userInfoExpand.setUserAddress(userAddress);
					userInfoExpand.setUserEmail(userEmail);
					userInfoExpand.setUserPosition(userPosition);
					userInfoExpand.setUserCompany(userCompany);
					userInfoExpand.setUserShow(userShow);
					dstUserInfoExpandService.updateForce(userInfoExpand);
				}

				//积分规则
				dstIntegralRuleService.execute(openid,"userCard");
			}
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("update dstUserInfoExpand list end .......");
		}catch(Exception e){
			log.error("update dstUserInfoExpand error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}

	/***
	 * 个人中心-日常统计
	 * @param request
	 * @return
	 */
	@RequestMapping("/dailyCount")
	@ResponseBody
	public ResultMap dailyCount(HttpServletRequest request){
		ResultMap result = new ResultMap();

		try{
			logger.info("query dailyCount dstUserInfoExpand  begin .......");

			String openid=request.getParameter("openid");
			//参数  默认
			if(StringUtils.isBlank(openid)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			//统计
			DstUserCountInfoVO visitDateLog = commonService.visitDateLog(openid);
			result.setAttribute("dto",visitDateLog);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);

			logger.info("query dailyCount dstUserInfoExpand  end .......");
		}catch(Exception e){
			log.error("query dailyCount dstUserInfoExpand error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
	
	/***
	 * 用户名片图片生成 保存
	 * @param request
	 * @return
	 */
	@RequestMapping("/userCardMarkLogo")
	@ResponseBody
	public ResultMap userCardMarkLogo(HttpServletRequest request) {
		ResultMap result = new ResultMap();

		try {
			long begin=System.currentTimeMillis();
			logger.info("userCardMarkLogo  begin .......");

			String openid = request.getParameter("openid");
			String create = request.getParameter("create");
			if (StringUtil.isNullOrEmptyStr(openid)) {
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			DstUserInfoExpandDTO dstUserInfoExpand = new DstUserInfoExpandDTO();
			dstUserInfoExpand.setUserOpenid(openid);
			dstUserInfoExpand.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoExpandDTO dto = dstUserInfoExpandService
					.queryListGetFirst(dstUserInfoExpand);

			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);
			
			// 目录
			String targerPath = new StringBuffer().append(ossUserCardPath)
				.append("/").append("userCard").append("/").append(DateUtil.formatDate(userinfo.getCreateDate(), "yyyyMMdd"))
				.append("/").append(openid).append("card").append(".jpg")
				.toString();
			// 用户的头像
			String userWchateImage = userinfo.getUserWechatImage();
			String headTemp=ossUserCardPath+"/tempHeadImage/"+DateUtil.getDate("yyyyMMdd")+"/"+userinfo.getUserWechatOpenid()+".jpg";
			String tempPath="/disk/upload/watertemp/"+userinfo.getUserWechatOpenid()+".jpg";
			
			if(StringUtils.isBlank(create)&&AliyunOssUtil.doesObjectExist(targerPath)){
			    result.setAttribute("imageUrl", CommonConstantUtil.OSS_PATH + targerPath+"?"+new Random().nextInt());
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				return result;
			}
			
			if(StringUtils.isBlank(dto.getUserName())){
				dto.setUserName(userinfo.getUserName());
			}
			if(StringUtils.isBlank(dto.getUserPosition())){
				dto.setUserPosition("未填");
			}
			if(StringUtils.isBlank(dto.getUserEmail())){
				dto.setUserEmail("未填");
			}
			if(StringUtils.isBlank(dto.getUserCompany())){
				dto.setUserCompany("未填");
			}
			if(StringUtils.isBlank(dto.getUserAddress())){
				dto.setUserAddress("未填");
			}
			if (dto != null && StringUtils.isNotBlank(dto.getUserCardImg())) {
				// 个人名片 名片生成背景图
				AliyunOssUtil.markUserCard(hasUserCardImage, targerPath, dto.getUserCardImg().replace(CommonConstantUtil.OSS_PATH, ""), tempPath, headTemp, userWchateImage,dto);
				logger.info("userCardMarkLogo card userWchateImage ......."+(System.currentTimeMillis()-begin)+"ms");
			} else {// 用户二维码为null的时候，直接用背景图
				AliyunOssUtil.markUserCard(noUserCardImage, targerPath, "", tempPath, headTemp, userWchateImage,dto);
			}
			logger.info("userCardMarkLogo card insert ......."+(System.currentTimeMillis()-begin)+"ms");
					
			result.setAttribute("imageUrl", CommonConstantUtil.OSS_PATH
					+ targerPath+"?"+new Random().nextInt());
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);

			logger.info("userCardMarkLogo text  end ......."+(System.currentTimeMillis()-begin)+"ms");
		} catch (Exception e) {
			log.error("userCardMarkLogo error!", e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
	
	
}
